package com.qf.service.impl;

import com.qf.mapper.PermissionMapper;
import com.qf.pojo.Permission;
import com.qf.service.PermissionService;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public ResultMsg queryAllPermission(Integer page, Integer limit) {
        if (page != null) page = page <= 1 ? 1 : page;
        List<Permission> permissions = permissionMapper.queryAllPermissions(page == null ? null : ((page - 1) * limit), limit);
        if (permissions.size() == 0) return ResultMsg.FAILED(201, "no data was found");
        return ResultMsg.SUCCESS(0, permissions, permissionMapper.queryPermissionCount().getPermissionId());
    }

    @Override
    public ResultMsg queryOnePermission(Integer permissionId) {
        if (permissionId == null) return ResultMsg.FAILED(203, "parameter 'permissionId' can not be bull");
        List<Permission> permissions = permissionMapper.queryPermission(permissionId);
        if (permissions.size() == 0) return ResultMsg.FAILED(201, "no data was found");
        return ResultMsg.SUCCESS(permissions.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg updatePermission(Permission permission) {
        if (permission.getPermissionId() == null)
            return ResultMsg.FAILED(203, "parameter 'permissionId' can not be null");
        if (permission.getPermissionName() == null)
            return ResultMsg.FAILED(205, "permission name can not be null");
        if (permissionMapper.updatePermission(permission) == 0)
            return ResultMsg.FAILED(201, "modify failed");
        return ResultMsg.SUCCESS();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg insertPermission(Permission permission) {
        if (permission.getPermissionName() == null)
            return ResultMsg.FAILED(205, "permission name can not be null");
        permission.setPermissionId(null);
        if (permissionMapper.insertPermission(permission) == 0)
            return ResultMsg.FAILED(201, "insert permission information to database failed");
        return ResultMsg.SUCCESS(0, permission, 0);
    }
}
